package org.example.base.exception;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.List;

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(xuechengPluesException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse customException(xuechengPluesException e){
        log.error("系统异常{}",e.getMessage(),e);
        String errMessage = e.getMessage();
        RestErrorResponse restErrorResponse=new RestErrorResponse(errMessage);
        return restErrorResponse;
    }
    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse exception(Exception e){

        //记录异常
        log.error("系统异常{}",e.getMessage(),e);

        //解析出异常信息
        RestErrorResponse restErrorResponse = new RestErrorResponse(CommonError.UNKOWN_ERROR.getErrMessage());
        return restErrorResponse;
    }
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public RestErrorResponse methodArgumentNotValidexception(MethodArgumentNotValidException e){
        BindingResult bindingResult=e.getBindingResult();
        //存放错误信息
        List<String> error=new ArrayList<>();
        bindingResult.getFieldErrors().stream().forEach(fieldError->{
            error.add(fieldError.getDefaultMessage());
        });
        //将错误信息拼接起来
        String errMessage= StringUtils.join(error,",");
        log.info("系统异常{}",errMessage,e.getMessage());
        RestErrorResponse restErrorResponse=new RestErrorResponse(errMessage);
        return restErrorResponse;
    }
}
